﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class Contact : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FillData();
            }
        }

        private void FillData()
        {
            var sql = "select Id,RoleName,Description from Roles";
            var dt = DbHelper.GetDataTable(sql);
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            FillData();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var rowIndex = e.RowIndex;
            var id = int.Parse(GetTheValueWtihColumnIndex(rowIndex, 1));


            var sql = string.Format("delete from Roles where Id={0}",  id);
            var res = DbHelper.AddOrUpdateOrDelete(sql);
            FillData();
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            FillData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var rowIndex = e.RowIndex;
            var id = int.Parse(GetTheValueWtihColumnIndex(rowIndex, 1));
            var roleName = GetTheValueWtihColumnIndex(rowIndex, 2);
            var des = GetTheValueWtihColumnIndex(rowIndex, 3);

            var sql = string.Format("update Roles set RoleName='{0}', Description='{1}' where Id={2}", roleName, des, id);
            var res = DbHelper.AddOrUpdateOrDelete(sql);
            GridView1.EditIndex = -1;
            FillData();
        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

        private string GetTheValueWtihColumnIndex(int rowIndex, int columnIndex)
        {
            var cont = GridView1.Rows[rowIndex].Cells[columnIndex];
            var txt = cont.Controls.Count > 0 ? ((TextBox)cont.Controls[0]).Text : cont.Text;
            return txt;
        }
    }
}